package com.xkcyy.one.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcyy.one.entity.Agent;
import com.xkcyy.one.entity.AgentTool;
import com.xkcyy.one.entity.Tool;
import com.xkcyy.one.exception.BusinessException;
import com.xkcyy.one.mapper.AgentToolMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 智能体工具关联服务类
 * 
 * @author yuand
 */
@Service
public class AgentToolService {

    private final AgentToolMapper agentToolMapper;
    private final AgentService agentService;
    private final ToolService toolService;

    @Autowired
    public AgentToolService(AgentToolMapper agentToolMapper, AgentService agentService, ToolService toolService) {
        this.agentToolMapper = agentToolMapper;
        this.agentService = agentService;
        this.toolService = toolService;
    }

    /**
     * 为智能体添加工具
     *
     * @param agentId 智能体ID
     * @param toolId  工具ID
     * @return 关联对象
     */
    public AgentTool addToolToAgent(Long agentId, Long toolId) {
        // 检查智能体是否存在
        agentService.getAgentById(agentId);

        // 检查工具是否存在
        toolService.getToolById(toolId);

        // 检查关联是否已存在
        LambdaQueryWrapper<AgentTool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentTool::getAgentId, agentId)
                .eq(AgentTool::getToolId, toolId);
        if (agentToolMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException("智能体已关联该工具");
        }

        // 创建关联对象
        AgentTool agentTool = new AgentTool();
        agentTool.setAgentId(agentId);
        agentTool.setToolId(toolId);

        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        agentTool.setCreateTime(now);
        agentTool.setUpdateTime(now);

        // 插入关联
        agentToolMapper.insert(agentTool);

        return agentTool;
    }

    /**
     * 批量添加工具到智能体
     *
     * @param agentId 智能体ID
     * @param toolIds 工具ID列表
     * @return 添加的工具ID列表
     */
    @Transactional
    public List<Long> addToolsToAgent(Long agentId, List<Long> toolIds) {
        List<Long> addedToolIds = new ArrayList<>();

        for (Long toolId : toolIds) {
            try {
                addToolToAgent(agentId, toolId);
                addedToolIds.add(toolId);
            } catch (BusinessException e) {
                // 如果工具已关联或不存在，忽略错误，继续处理下一个
                continue;
            }
        }

        return addedToolIds;
    }

    /**
     * 从智能体移除工具
     *
     * @param agentId 智能体ID
     * @param toolId  工具ID
     */
    public void removeToolFromAgent(Long agentId, Long toolId) {
        // 检查关联是否存在
        LambdaQueryWrapper<AgentTool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentTool::getAgentId, agentId)
                .eq(AgentTool::getToolId, toolId);

        if (agentToolMapper.selectCount(queryWrapper) == 0) {
            throw new BusinessException("智能体未关联该工具");
        }

        // 删除关联
        agentToolMapper.delete(queryWrapper);
    }

    /**
     * 批量移除工具从智能体
     *
     * @param agentId 智能体ID
     * @param toolIds 工具ID列表
     * @return 移除的工具ID列表
     */
    @Transactional
    public List<Long> removeToolsFromAgent(Long agentId, List<Long> toolIds) {
        List<Long> removedToolIds = new ArrayList<>();

        for (Long toolId : toolIds) {
            try {
                removeToolFromAgent(agentId, toolId);
                removedToolIds.add(toolId);
            } catch (BusinessException e) {
                // 如果工具未关联，忽略错误，继续处理下一个
                continue;
            }
        }

        return removedToolIds;
    }

    /**
     * 获取智能体关联的工具列表
     *
     * @param agentId 智能体ID
     * @return 工具列表
     */
    public List<Tool> getToolsByAgentId(Long agentId) {
        // 检查智能体是否存在
        agentService.getAgentById(agentId);

        // 获取智能体关联的工具ID列表
        List<Long> toolIds = agentToolMapper.selectToolIdsByAgentId(agentId);

        if (toolIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取工具详情
        return toolIds.stream()
                .map(toolService::getToolById)
                .collect(Collectors.toList());
    }

    /**
     * 获取使用工具的智能体列表
     *
     * @param toolId 工具ID
     * @return 智能体列表
     */
    public List<Agent> getAgentsByToolId(Long toolId) {
        // 检查工具是否存在
        toolService.getToolById(toolId);

        // 获取使用工具的智能体ID列表
        List<Long> agentIds = agentToolMapper.selectAgentIdsByToolId(toolId);

        if (agentIds.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取智能体详情
        return agentIds.stream()
                .map(agentService::getAgentById)
                .collect(Collectors.toList());
    }

    /**
     * 清空智能体的所有工具
     *
     * @param agentId 智能体ID
     */
    public void clearAgentTools(Long agentId) {
        // 检查智能体是否存在
        agentService.getAgentById(agentId);

        // 删除智能体的所有工具关联
        LambdaQueryWrapper<AgentTool> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgentTool::getAgentId, agentId);
        agentToolMapper.delete(queryWrapper);
    }
}